import React, { useEffect, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import styles from './index.module.less';

const FTD = (props) => {
  const { className, centerFrequency, data, selectedItemKey, onSelectionChange } = props;

  const sumOfDurationCountRef = useRef(0);

  const options = useRef({ bw: 10, ms: 5 }).current;

  const [cols, setCols] = useState('repeat(12, minmax(0, 1fr))');

  useEffect(() => {
    if (data) {
      const { ms } = options;
      let sum = 0;
      data.forEach((d) => {
        const { duration } = d;
        sum += Math.floor(duration / ms) + (duration % ms > 0 ? 1 : 0);
      });
      setCols(Math.min(Math.max(sum, 12), 24));
    }
  }, [data]);

  const getTiles = () => {
    const { bw, ms } = options;
    const tiles = data?.map((d) => {
      const { frequency, bandwidth, occurrence, duration, serialNumber, dutyCycle, velocity, probability } = d;
      const df = frequency - centerFrequency;
      const h = Math.ceil(bandwidth / 1000 / bw);
      const i = 4 - Math.floor(df / bw) + (h > 2 ? Math.floor(h / 2) : 0);
      const w = Math.floor(duration / ms) + (duration % ms > 0 ? 1 : 0);
      const j = sumOfDurationCountRef.current + 1;
      sumOfDurationCountRef.current += w;
      return (
        <div
          key={serialNumber}
          className={classnames(styles.tile, selectedItemKey === serialNumber ? styles.selected : null)}
          onClick={() => {
            onSelectionChange(selectedItemKey === serialNumber ? null : serialNumber);
          }}
          style={{
            gridRowStart: i - h < 1 ? 1 : i - (h - 1),
            gridRowEnd: i + 1,
            gridColumnStart: j,
            gridColumnEnd: j + w,
          }}
          title={(() => {
            let title = `频率:${frequency} MHz\r\n`;
            title += `带宽:${bandwidth} kHz\r\n`;
            title += `起跳时间:${(occurrence || new Date().getTime()) / 1e6}\r\n`;
            title += `驻留时长:${duration || '--'} ms\r\n`;
            title += `占空比:${dutyCycle || '--'} %\r\n`;
            title += `速率:${velocity || '--'} HOPS/s\r\n`;
            title += `概率:${probability || '--'} %\r\n`;
            return title;
          })()}
        />
      );
    });
    sumOfDurationCountRef.current = 0;
    return tiles;
  };

  return (
    <div className={classnames(styles.root, className)}>
      <div className={styles.ys} title="MHz">
        {[-4, -3, -2, -1, 0, 1, 2, 3, 4].reverse().map((y) => {
          return <div key={y}>{centerFrequency + y * 10}</div>;
        })}
      </div>
      <div className={styles.tiles} style={{ gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))` }}>
        {getTiles()}
        <div className={styles.grid} style={{ backgroundSize: `calc(100% / ${cols}) calc(100% / 8)` }} />
      </div>
      <div className={styles.ts} title="ms">
        {new Array(cols + 1).fill(0).map((_t, i) => {
          return (
            // eslint-disable-next-line react/no-array-index-key
            <div key={i}>
              <div>{i * 5}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

FTD.defaultProps = {
  className: null,
  centerFrequency: null,
  data: null,
  selectedItemKey: null,
  onSelectionChange: () => {},
};

FTD.propTypes = {
  className: PropTypes.any,
  centerFrequency: PropTypes.any,
  data: PropTypes.any,
  selectedItemKey: PropTypes.any,
  onSelectionChange: PropTypes.func,
};

export default FTD;
